<script setup lang="ts">
import { QuillEditor, Quill } from "@vueup/vue-quill";
import { defineEmits, defineProps } from "vue";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
// import ImageUploader from "quill-image-uploader";
// import http from "@/utils/request/httpRequest";
import { reactive, ref, toRaw, toRefs, watch } from "vue";
import http from "@/utils/request/httpRequest.ts";
import {getBaseURL, windowURL} from "@/utils";

// Quill.register("modules/ImageUploader", ImageUploader);

const props = defineProps<{
  modelValue: string;
  readOnly: boolean; // 添加 readOnly 属性
}>();

const { modelValue, readOnly } = toRefs(props);

const emit = defineEmits(["update:modelValue"]);

const quillRef = ref();

const quillEditorInputFileRef = ref<HTMLDivElement>();

/** 文件上传loading */
const uploadLoading = ref(false);

const content = ref("");

const myOptions = reactive({
  modules: {
    toolbar: {
      container: [
        ["bold", "italic", "underline", "strike"],
        ["blockquote", "code-block"],
        [{ header: 1 }, { header: 2 }],
        [{ list: "ordered" }, { list: "bullet" }],
        [{ script: "sub" }, { script: "super" }],
        [{ indent: "-1" }, { indent: "+1" }],
        [{ direction: "rtl" }],
        [{ size: ["small", false, "large", "huge"] }],
        ["image"],
      ],
      handlers: {
        lineHeight: function (value) {
          const editor = quillRef.value.getQuill();
          if (value) {
            editor.format("lineHeight", value);
          }
        },
        image: function () {
          quillEditorInputFileRef.value?.click();
        }
      },
    },
    /*ImageUploader: {
      upload: (file) => {
        return new Promise((resolve, reject) => {
          const formData = new FormData();
          formData.append("file", file);


          http
              .post("file/uploadImg", formData)
              .then((response) => {
                if (getBaseURL()) {
                  const fullUrl = `${windowURL()}${response.data}`;
                  resolve(fullUrl);
                }
              })
              .catch((error) => {
                reject(error);
              });
        });
      },
    },*/
  },
  placeholder: "请输入内容...",
  readOnly: false, // 设置 readOnly 属性
});

const setValue = () => {
  // 用于设置双向绑定值
  const text = toRaw(quillRef.value).getHTML();
  emit("update:modelValue", text);
};

function init(data: string) {
  content.value = data;
  if (data.length === 0) {
    toRaw(quillRef.value) && toRaw(quillRef.value).setContents("");
  }
}

function onFileChange(event: Event) {
  const files = (event.target as HTMLInputElement).files!;
  let file: File | null = null;
  if (files.length <= 0) {
    file = null;
    return;
  }
  file = files[0]; // 只取第一个文件
  uploadLoading.value = true;

  const formData = new FormData();
  formData.append("file", file);

  http
      .post("file/uploadImg", formData)
      .then((response) => {
        if (getBaseURL()) {
          const fullUrl = `http://www.hbzwfw.gov.cn/competition${response.data}`;
          const range = quillRef.value?.getQuill().selection.savedRange.index
          quillRef.value?.getQuill().insertEmbed(range, "image", fullUrl);
          quillRef.value?.getQuill().setSelection(range + 1);
          uploadLoading.value = false;
        }
      })
}

const clear = () => {
  content.value = "<p></p>";
};
defineExpose({
  init,
  clear,
});
</script>

<template>
  <div style="width: 100%;">
    <QuillEditor
        style="height: 500px"
        ref="quillRef"
        v-model:content="content"
        :options="myOptions"
        contentType="html"
        @update:content="setValue"
    />
    <input class="quill-editor-input-file" ref="quillEditorInputFileRef" type="file" accept="image/*" @change="onFileChange" />
  </div>
</template>

<style scoped lang="scss">
.quill-editor-input-file {
  display: none;
}
</style>
